//
//  HJUserAccountViewModel.swift
//  WeiBo
//
//  Created by 韩俊 on 15/12/8.
//  Copyright © 2015年 HanJun. All rights reserved.
//

import UIKit

class HJUserAccountViewModel {
    
    // ViewModel 引用 Model (返过来不可以)
    var userAccount: HJUserAccount?
    
    
    
    // 是否登录
    var userLogon: Bool {
        return accessToken != nil
    }
    
    // 只读取属性
    // 返回当前用户的accessToken
    var accessToken: String? {
        
        // 从 userAccount 取出 accessToken
        // 如果没有 return nil
        // 如果取出来存在,还有得判断是否过期
        if let accessToken = userAccount?.access_token where !isExpires {
            // 判断是否过期
            return accessToken
        }
        return nil
    }
    
    // 返回 true 代表过期, false 没有过期
    // 写 getOnly 的原因是代表,我们判断的 accessToken 是否过期是根据当前时间变化计算出来的
    var isExpires: Bool {
        
        guard let expiresDate = userAccount?.expiresDate else {
            return true
        }
        
        // 通过过期时间计算出比过期时间少1的时间
        //        let newDate = expiresDate.dateByAddingTimeInterval(0)
        
        // 当前时间与 expiresDate 进行对比
        // 如果当前时间 不大于 expiresDate 过期时间,是代表不过期:false
        if NSDate().compare(expiresDate) == NSComparisonResult.OrderedAscending {
            return false
        }
        return true
    }
    
    // 全局访问点
    static let sharedAccount: HJUserAccountViewModel = HJUserAccountViewModel()
    
    // 构造方法私有化,外界不能直接通过 类名() 初始化对象
    private init(){
        // 从归档里面解档
        userAccount = loadUserAccount()
    }
}
// MARK: - OAuth 登录请求
extension HJUserAccountViewModel {
    
    // MARK: - 获取AccessToken
    func loadAccessToken(code:String, complete:(isSuccess:Bool)->()) {
        
        
        HJNetworkTools.shareTools.loadAccessToken(code) { (response, error) -> () in
            
            if error != nil {
                
                print("请求错误:\(error)")
                complete(isSuccess: false)
                
                return
            }
            
            guard let dic = response as? [String:AnyObject] else {
                
                print("不是字典")
                return
            }
            
            let account = HJUserAccount(dic: dic)
            
            self.userAccount = account
            
            //            complete(isSuccess: true)
            
            self.loadUserInfo(account.uid!, accessToken: account.access_token!, complete: complete)
        }
        
    }
    
    private func loadUserInfo(uid:String, accessToken:String, complete:(isSuccess:Bool)
        ->())
    {
        
        HJNetworkTools.shareTools.loadUserInfo(uid, accessToken: accessToken) { (response, error) -> () in
            
            if error != nil {
                
                print("请求错误")
                complete(isSuccess: false)
            }
            
            guard let dic = response as? [String:AnyObject] else {
                
                print("不是字典")
                return
            }
            
            self.userAccount?.screen_name = dic["screen_name"] as? String
            self.userAccount?.avatar_large = dic["avatar_large"] as? String
            print(self.userAccount?.avatar_large)
            self.userAccount?.saveAccout()
            
            complete(isSuccess: true)
        }

    }
    
}

// MARK: - 归档与解档当前对象
extension HJUserAccountViewModel {
    
    func saveAccessToken(account:HJUserAccount) {
        
        let file = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("useraccount.archive")
        
        NSKeyedArchiver.archiveRootObject(account, toFile: file)

    }
    
    //解档
    func loadUserAccount() -> HJUserAccount? {
        
        let file = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("useraccount.archive")
        
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(file) as? HJUserAccount
        
        return result
    }
    
}

